<?php
error_reporting(E_ALL & ~E_NOTICE);
require_once("xmlobj.php");
require_once("xmlstream.php");
require_once("logging.php");

class XMPP extends XMLStream {
	var $server;
	var $user;
	var $password;
	var $resource;
	var $fulljid;
	static private $ver_from;
	static private $ver_type;
	static private $ver_to;
	static private $ver_chat_type;
	static private $tconf;
	static private $start1;
	static $r1;
    var $role_st = array();


    private $name;


	function XMPP($host, $port, $user, $password, $resource, $server=Null, $printlog=False, $loglevel=Null) {
		$this->XMLStream($host, $port, $printlog, $loglevel);
		$this->user = $user;
		$this->password = $password;
		$this->resource = $resource;
		if(!$server) $server = $host;
		$this->stream_start = '<stream:stream to="' . $server . '" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" version="1.0">';
		$this->stream_end = '</stream:stream>';
		$this->addHandler('features', 'http://etherx.jabber.org/streams', 'features_handler');
		$this->addHandler('success', 'urn:ietf:params:xml:ns:xmpp-sasl', 'sasl_success_handler');
		$this->addHandler('failure', 'urn:ietf:params:xml:ns:xmpp-sasl', 'sasl_failure_handler');
		$this->addHandler('proceed', 'urn:ietf:params:xml:ns:xmpp-tls', 'tls_proceed_handler');
		$this->default_ns = 'jabber:client';
		$this->addHandler('message', 'jabber:client', 'message_handler');
		$this->addHandler('presence', 'jabber:client', 'presence_handler');

	}

	function message_handler($xml) {
		$payload['type'] = $xml->attrs['type'];
		//if(!$paytload['type']) $payload['type'] = 'chat';
		if($paytload['type']=='error') $payload['type'] = 'groupchat';
		$payload['from'] = $xml->attrs['from'];
		$payload['body'] = $xml->sub('body')->data;
		$this->log->log("Message: {$xml->sub('body')->data}", LOGGING_DEBUG);
		$this->event('message', $payload);
	}

	function message($to, $body, $type='chat', $subject=Null) {
		$to = htmlspecialchars($to);
		$body = htmlspecialchars($body);
		$subject = htmlspecialchars($subject);
		$out = "<message from='{$this->fulljid}' to='$to' type='$type'>";
		if($subject) $out .= "<subject>$subject</subject>";
		$out .= "<body>$body</body></message>";
		$this->send($out);
	}

function presence($status=Null, $show='available', $to=Null) {
		$to = htmlspecialchars($to);
		$status = htmlspecialchars($status);
		if($show == 'unavailable') $type = 'unavailable';
		$out = "<presence";
		if($to) $out .= " to='$to'";
		if($type) $out .= " type='$type'";
		if($show == 'available' and !$status) {
			$out .= "/>";
		} else {
			$out .= ">";
			if($status) $out .= "<status>$status</status>";
			if($show != 'available') $out .= "<show>$show</show>";
			$out .= "</presence>";
		}
		$this->send($out);
	}

public function presence_handler($xml) {
		$payload['type'] = $xml->attrs['type'];
		if(!$payload['type']) $payload['type'] = 'available';
		$payload['show'] = $xml->sub('show')->data;
		if(!$payload['show']) $payload['show'] = $payload['type'];
		$payload['from'] = $xml->attrs['from'];
		$payload['status'] = $xml->sub('status')->data;

	    if($xml->hassub('x'))
        {
	      	//$payload['role'] = $xml->sub(0)->sub('item')->attrs['role'];
	      	//$payload['jid'] = $xml->sub(0)->sub('item')->attrs['jid'];
	      	//$payload['affiliation'] = $xml->sub(0)->sub('item')->attrs['affiliation'];
	      	//$this->message ('narkoz@localhost', $payload['role'], 'chat');
        	$tmp[0] = $xml->sub('x');
			$tmp=print_r($tmp[0],true);
			$respage=str_replace('<br>',"\n",$respage);
			$tmp=str_replace(" ",'',$tmp);
			$tmp=explode("(",$tmp);
			$tmp=str_replace("\n",'',$tmp);
			$x_jid = substr ($tmp[5], strpos ($tmp[5], '[jid]')+7, strpos ($tmp[5], '[affiliation]')-7);
			$x_role = substr ($tmp[5], strpos ($tmp[5], '[role]')+8, strlen ($tmp[5]));
			$x_role = substr ($x_role, 0, strpos ($x_role, ')'));
			$payload['role'] = $x_role;
			$payload['jid'] = $x_jid;

			//$this->event('presence', $payload);
	    	//$this->message ('narkoz@localhost', $payload['from'].$payload['jid'].$payload['role'], 'chat');
	    }

$key = array_search($payload['from'], $this->role_st);

//print_r ($this->role_st);
//$this->message ('narkoz@localhost', $payload['from'].' = '.$key, 'chat');

if ($key>0)
{
if (strpos ($payload['from'],'conference') > 1)
{
if (strlen ($payload['role']) >1 )
{
if (strlen ($payload['jid']) >1 )
{
if (strpos ($payload['jid'],'@') > 1)
{
$this->role_st[$key] = $payload['from'];
$this->role_st[$key+1] = $payload['jid'];
$this->role_st[$key+2] = $payload['role'];
}
}
}
}
}
else
{
if (strpos ($payload['from'],'conference') > 1)
{
if (strlen ($payload['role']) >1 )
{
if (strlen ($payload['jid']) >1 )
{
if (strpos ($payload['jid'],'@') > 1)
{
array_push ($this->role_st, $payload['from']);
array_push ($this->role_st, $payload['jid']);
array_push ($this->role_st, $payload['role']);
}
}
}
}
}

//$this->message ('narkoz@localhost',$payload['from'].$payload['jid'].$payload['role'].$payload['affiliation'], 'chat');
		$this->r1 = $this->role_st;
	    $this->event('presence', $payload);
	}


function show ($show='available', $to=Null) {
		$to = htmlspecialchars($to);
		$status = htmlspecialchars($status);
		if($show == 'unavailable') $type = 'unavailable';
		$out = "<presence";
		if($to) $out .= " to='$to'";
		if($type) $out .= " type='$type'";
		$out .= ">";
		$out .= '<show>'.$show.'</show>';
		$out .= "</presence>";
		$this->send($out);
	}


function joinc($to) {
		$to = htmlspecialchars($to);
		$out = '<presence to="'.$to.'" >'. '<x xmlns="http://jabber.org/protocol/muc"><history maxchars="0" maxstanzas="0"/></x></presence>';
		$this->send($out);
	}



function kick($to, $nick,$reason) {
		$out = '<iq type="set" to="'.$to.'"><query xmlns="http://jabber.org/protocol/muc#admin"><item nick="'.$nick.'" role="none"><reason>'.$reason.'</reason></item></query></iq>';
		$this->send($out);
	}


function confquit($to) {
		$to = htmlspecialchars($to);
		$out = '<presence type="unavailable" to="'.$to.'" />';
		$this->send($out);
	}

public function vinfo($from, $to, $msgtype,$what) {
		$to = htmlspecialchars($to);
		$from = htmlspecialchars($from);
		$id = $this->getId();
		$this->ver_from = $from;
		$this->ver_to = $to;
        $this->ver_chat_type = $msgtype;
        $this->ver_type = $what;

      	//start ping timer
   		if ($what == 'ping')
		{
		//ping timer
		$start1=gettimeofday();
		$this->start1=$start1;
		for($i=0; $i<10000; $i++)
		{
		// do nothing
		}

		$out = '<iq from="'.$to.'" to="'.$from.'" id="'.$id.'" type="get"><query xmlns="jabber:iq:version"/></iq>';
		$this->send($out);
		//$this->message ('narkoz@localhost', $this->$start1, 'chat');
		}


	}


public function vinfo2($to, $from, $tconf, $msgtype,$what) {
		$to = htmlspecialchars($to);
		$from = htmlspecialchars($from);
		$id = $this->getId();
		$this->tconf =$tconf;
        $this->ver_chat_type = $msgtype;
        $this->ver_type = $what;

       	//start ping timer
   		if ($what == 'ping')
		{
		//ping timer
		$this->start1=gettimeofday();
		for($i=0 ; $i<10000 ; $i++ )
		{
		// do nothing
		}
		}

		$out = '<iq from="'.$from.'" to="'.$from.'" id="'.$id.'" type="get"><query xmlns="jabber:iq:version"/></iq>';
		$this->send($out);
		//$this->message ('narkoz@localhost', $to.$from.$tconf.$msgtype.$what, 'chat');
	}




	function features_handler($xml) {
		if($xml->hassub('starttls')) {
			$this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>");
		} elseif($xml->hassub('bind')) {
			$id = $this->getId();
			$this->addIdHandler($id, 'resource_bind_handler');
			$this->send("<iq xmlns=\"jabber:client\" type=\"set\" id=\"$id\"><bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"><resource>{$this->resource}</resource></bind></iq>");
		} else {
			$this->log->log("Attempting Auth...");
			$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode("\x00" . $this->user . "\x00" . $this->password) . "</auth>");
		}
	}

	function sasl_success_handler($xml) {
		$this->log->log("Auth success!");
		$this->reset();
	}

	function sasl_failure_handler($xml) {
		$this->log->log("Auth failed!", LOGGING_ERROR);
		$this->disconnect();
	}

	function resource_bind_handler($xml) {
		if($xml->attrs['type'] == 'result') {
			$this->log->log("Bound to " . $xml->sub('bind')->sub('jid')->data);
			$this->fulljid = $xml->sub('bind')->sub('jid')->data;
		}
		$id = $this->getId();
		$this->addIdHandler($id, 'session_start_handler');
		$this->send("<iq xmlns='jabber:client' type='set' id='$id'><session xmlns='urn:ietf:params:xml:ns:xmpp-session' /></iq>");
	}

	function session_start_handler($xml) {
		$this->log->log("Session started");
		$this->event('session_start');
	}

	function tls_proceed_handler($xml) {
		$this->log->log("Starting TLS encryption");
		stream_socket_enable_crypto($this->socket, True, STREAM_CRYPTO_METHOD_TLS_CLIENT);
		$this->reset();
	}


public function income_iq($xml)
{

//version start
if ($this->ver_type == 'ver')
{
$this->ver_type = 'none';
$tmp['type'] = $xml->attrs['type'];
if($xml->hassub('query'))
{$tmp['name'] = $xml->sub(0)->sub('name')->data;
$tmp['version'] = $xml->sub(0)->sub('version')->data;
$tmp['os'] = $xml->sub(0)->sub('os')->data;

if ($this->ver_chat_type == 'chat') $this->message ($this->ver_from, $tmp['name'].' '.$tmp['os'], $this->ver_chat_type);
if ($this->ver_chat_type == 'groupchat')
{if (empty ($tmp['name'])) $tmp['name']='Not found!';
$this->message ($this->tconf, $tmp['name'].' '.$tmp['os'], $this->ver_chat_type);
}}
}
//version end

//ping
if ($this->ver_type == 'ping')
{
$end1=gettimeofday();
$totaltime1 = (float)($end1['sec'] - $this->start1['sec']) + ((float)($end1['usec'] - $this->start1['usec'])/1000000);
if ($this->ver_chat_type == 'chat') $this->message ($this->ver_from, 'Pong: '.substr ($totaltime1, 0,4).' sec.', $this->ver_chat_type);
if ($this->ver_chat_type == 'groupchat') $this->message ($this->tconf, 'Pong: '.substr ($totaltime1, 0,4).' sec.', $this->ver_chat_type);
$this->ver_type = 'none';
}

}

}
?>
